import { AddressModel } from '../../../models/AddressModel.js'
let Address = new AddressModel()
let App = getApp()

Page({

    /**
     * 页面的初始数据
     */
    data: {
      checked: true,
      addressList:[],
      openId:'',

    },
      /**
     * 生命周期函数--监听页面加载
     */
    _init:function(){
      this._getAddress()
    },
    _getAddress:async function(){
        let address = {
          openId:this._getOpenId()
        }
        console.log('openid',address)
        let res = await Address.getAddress(address)
        this.setData({
          addressList:res
        })
        console.log('address',res)
    },
    _getOpenId:function(){
      let openId = App.globalData.openId
      this.setData({openId})
      return openId
    },
    onLoad: function () {
      // 2、调用云函数获取openId
     this._init()
    
   },
   onShow:function(){
    this._init()
   },
    //    编辑地址信息
   editAddress:function(e){
     let addressId = e.detail.addressId
     wx.navigateTo({
       url: '../editAddress/editAddress?addressId=' + addressId,
     })
      console.log('e',e)
   },
   deleteAddress:async function(e){
    let addressId = e.detail.addressId
    await Address.deleteAddress(addressId)
    this.onShow()
   },
    // 获取默认地址id
    _getDefaultAddressId:function(){
      let addressList = this.data.addressList
      let addressId = ''
      for(let i=0;i<addressList.length;i++){
        if(addressList[i].default){
          addressId = addressList[i]._id
          break
        }
      }
      return addressId;
     
    },
   
    //   设置默认地址
   setDefaultAddress:async function(e){
    let addressId = e.detail.addressId
    let address = {
        default:true
    }
    let preDefaultAddressId = this._getDefaultAddressId()
    // 如果存在默认地址，则将原默认地址更新为非默认地址
    let preAddress = {
      default:false
    }
    // 存在默认地址
    if(preDefaultAddressId.length > 0){
      await Address.updateAddress(preAddress, preDefaultAddressId)
    }
    // 将选中的地址设为默认地址
    await Address.updateAddress(address, addressId)
    this.onShow()
 
   },
   addAddress:function(e){
    wx.navigateTo({
      url: '/pages/address/addAddress/addAddress',
    })
  },

   
   
   

})

